<template>
  <section class="flow-edit-box" v-loading.fullscreen="launching">
    <a-tabs class="tabs-wrap" :activeKey="activeKey" @change="tabChange">
      <template #extra>
        {{ model.name }}
      </template>
      <a-tab-pane key="1" title="表单信息"> </a-tab-pane>
      <!-- <a-tab-pane key="2" title="原始流程"></a-tab-pane> -->
      <a-tab-pane key="3" title="审批流程"> </a-tab-pane>
    </a-tabs>

    <a-row class="flow-main">
      <a-col :xs="24" :sm="24" :md="24" :lg="16" v-if="activeKey == '1'">
        <a-card class="form-main_box">
          <FormIframe
            ref="formIframe"
            v-if="flowFormId"
            :model="model"
            @getForm="onFormData"
          />
        </a-card>
      </a-col>
      <a-col v-if="activeKey == '2'">
        <Flow ref="flowBox"></Flow>
      </a-col>
      <a-col v-if="activeKey == '3' && model.id">
        <a-card style="margin: 0 16px">
          <flow-launch
            ref="flowLaunch"
            :modelId="model.id"
            @onCancel="onClose()"
            @onSuccess="onClose()"
          >
          </flow-launch>
        </a-card>
      </a-col>
    </a-row>

    <div class="foot-nav">
      <a-space>
        <!-- <a-button @click="back">
          <template #icon>
            <icon-undo />
          </template>
          返 回
        </a-button> -->
        <template v-if="activeKey != '2'">
          <a-button
            v-if="buttonAuth.save"
            @click="submit(FLAG[0])"
            :loading="launching"
          >
            保 存
          </a-button>
          <a-button
            v-if="buttonAuth.submit"
            type="primary"
            @click="submit(FLAG[1])"
            :loading="launching"
          >
            提 交
          </a-button>
          <a-button @click="reset">重 置</a-button>
        </template>
      </a-space>
    </div>
  </section>
</template>

<script setup>
import {
  onBeforeMount,
  onMounted,
  onBeforeUnmount,
  ref,
  toRaw,
  nextTick,
} from "vue";
import { useFlowStore } from "@/stores/index";
import { Notification, Message, Modal } from "@arco-design/web-vue";
import { IconLeft, IconUndo } from "@arco-design/web-vue/es/icon";
import OrganApi from "@/api/OrganApi";
import FlowManApi from "@/api/FlowManApi";
import FlowInstApi from "@/api/FlowInstApi";
import Flow from "@/components/flow/index.vue";
import formatDef from "@/components/flow/common/formatDef.js";
import { cleanUnrequiredWidget } from "@/components/flow/common/FormExp";
import { useRouter, useRoute } from "vue-router";
import FormIframe from "./form-iframe.vue"; // 表单
import { checkDevice } from "@/utils/index";
import { setToken } from "@/utils/auth";
import Cookies from "js-cookie";
// 流程节点
import FlowLaunch from "./flow-launch.vue";

let { flowDefinition, setPersonFields } = useFlowStore();
const router = useRouter();
const route = useRoute();

const model = ref("");
const flowFormId = ref("");
const { formId, modelId,token } = route.query;
let launching = ref(false); // 流程提交中
let flowBox = ref(); // 流程组件
let flowLaunch = ref(); // 流程组件
const buttonAuth = ref({});

// 返回
const back = () => {
  router.go(-1);
};

// 重置
const reset = () => {
  Modal.confirm({
    title: "重置提示",
    content: "点击该按钮将清除表单中输入的数据，确定要重置？",
    onOk: () => {
      flowFormId.value = "";
      nextTick(() => {
        flowFormId.value = formId;
      });
    },
  });
};

const formIframe = ref();
const FLAG = {
  0: "save",
  1: "start",
};
const status = ref(FLAG[1]);
// 点击提交
const submit = (flag) => {
  console.log("flag", flag);
  status.value = flag;
  // 获取发起人自选人
  if (flowLaunch.value) {
    console.log(
      "flowNodeDesignees",
      flowLaunch.value?.flowNodeDesignees,
      flowLaunch.value?.selfChoiceList
    );
    const keys = Object.keys(flowLaunch.value?.flowNodeDesignees);
    const selfChoiceList = flowLaunch.value?.selfChoiceList;
    if (keys.length != selfChoiceList.length) {
      Notification.error("自选执行人节点未选择执行人");
      return;
    }
  }

  // 先获取表单数据
  if (formIframe.value) {
    formIframe.value.sendIframeData("get");
  }
};
const onFormData = (data) => {
  console.log("onFormData", data);
  // 提交数据到后台
  startFlow(data);
};

// 收到表单数据提交发起流程
const startFlow = (formData) => {
  console.log("form data", formData);
  if (!formData.data) {
    Notification.warning(`未获取到表单数据`);
    return;
  }
  const { key, id, name, version, formName } = model.value;
  launching.value = true;
  if (status.value == FLAG[0]) {
    FlowInstApi.flowSave({
      modelId: id,
      modelKey: key,
      formData,
      variable: flowLaunch.value?.flowNodeDesignees || {},
      modelName: name,
      modelVersion: version,
      formName,
    })
      .then((resp) => {
        launching.value = false;
        if (resp.code == 0) {
          Notification.success(`流程${name}已保存至"我的草稿"中`);
          back();
        }
      })
      .catch(() => {
        launching.value = false;
      });
  } else {
    FlowInstApi.flowStart({
      operateType: "START",
      modelId: id,
      modelKey: key,
      formData,
      variable: flowLaunch.value?.flowNodeDesignees || {},
    })
      .then((resp) => {
        launching.value = false;
        if (resp.code == 0) {
          Notification.success(`流程${name}已发起`);
          back();
        }
      })
      .catch(() => {
        launching.value = false;
      });
  }
};

// 查询发起节点按钮权限
const getButtonAuth = (modelId) => {
  FlowInstApi.nodeQuery({
    modelId,
    nodeType: "START_ENV",
  })
    .then((resp) => {
      if (resp.code == 0) {
        const data = resp.data.records;
        buttonAuth.value = data.length && data[0].buttonAuth;
        console.log("buttonAuth", buttonAuth.value);
      }
    })
    .catch(() => {});
};

// tab标签
const activeKey = ref("1");
const tabChange = (key) => {
  if (key == "2") {
    let { nodeConfig, flowWidgets } = flowDefinition;
    cleanUnrequiredWidget(flowWidgets, nodeConfig);
  }
  activeKey.value = key;
};

// 获取模型数据
const getModelData = (id) => {
  FlowManApi.getModelById(id).then((resp) => {
    if (resp.code == 0) {
      model.value = resp.data;
      formatDef.formatFlowJson(resp.data);
    }
  });
};
// 获取表单设置人员控件
const getFormData = (id) => {
  FlowManApi.getFormsById(id).then((resp) => {
    if (resp.code == 0) {
      setPersonFields(resp.data?.formResource?.personFields);
    }
  });
};
onMounted(async () => {});
onBeforeMount(async () => {
  if (checkDevice() && token) {
    setToken(token);
    Cookies.set("token", token, { SameSite: "strict" });
  }
  OrganApi.loadOrgan();
  if (modelId) {
    getModelData(modelId);
    getButtonAuth(modelId);
    getFormData(formId);
    flowFormId.value = formId;
  }
});
</script>

<style lang="less" scoped>
@import "@/styles/variables.module.less";

.flow-edit-box {
  position: relative;
  height: 100%;
  background-color: @MainContentBg;
  overflow: hidden;
  :deep(.tabs-wrap) {
    .arco-tabs-nav {
      background-color: #fff;

      .arco-tabs-nav-extra {
        margin-right: 16px;
      }
    }
  }
  .flow-main {
    height: calc(100% - 77px - 56px);
    overflow-y: auto;
    display: flex;
    justify-content: center;

    .form-main_box {
      // width: 1080px;
      margin: 0 auto;
    }
  }

  .foot-nav {
    background-color: #fff;
    text-align: center;
    padding: 15px;
    margin-top: 16px;
  }
}
</style>
